package org.example.javaee_demo1.controller;


import org.example.javaee_demo1.common.Result;
import org.example.javaee_demo1.pojo.User;
import org.example.javaee_demo1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        String username = user.getUsername();
        String password =user.getPassword();
        System.out.println(username);
        System.out.println(password);
        if(!userService.isexistname(username,password)){
            return Result.error("用户不存在或密码错误");
        }
        return Result.success("success");

    }
    /**
     * 注册
     */
    @RequestMapping("/add")
    public Result adduser(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        System.out.println(username);
        System.out.println(password);
//        // 检查用户名是否已存在
//        if(userService.isexistname(username,password)) {
//            return Result.error("用户名已存在");
//        }
        
        // 注册新用户
        boolean success = userService.addUser(user);
        if(!success) {
            return Result.error("注册失败");
        }
        
        return Result.success("注册成功");
    }
    /**
     * 获取用户列表
     * @return
     */
    @RequestMapping("/userlist")
    public Result getUser() {

        List<User> userList=userService.getUser();
        return Result.success(userList);

    }
    
    /**
     * 删除用户
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        boolean success = userService.deleteUser(id);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    @RequestMapping("updata/{id}")
    public Result updateUser(User user) {
        boolean success = userService.updateUser(user);
        return success ? Result.success("修改成功") : Result.error("修改失败");
    }

}
